import Vue from "vue";
import VueRouter from "vue-router";


Vue.use(VueRouter);

const routes = [
  {
    path: "/index",
    component: () => import("../pages/index.vue"),
    children: [
      {
        path: "/home",
        component: () => import("../views/home.vue"),
        meta:{
          title:'小u商城'
        }
      },
      {
        path: "/cate",
        component: () => import("../views/cate.vue"),
        meta:{
          title:'分类'
        }
      },
      {
        path: "/cart",
        component: () => import("../views/cart.vue"),
        meta:{
          title:'购物车'
        }
      },
      {
        path: "/mine",
        component: () => import("../views/mine.vue"),
        meta:{
          title:'我的'
        }
      },
      {
        path: "",
        redirect: "/home",
      },
    ],
  },
  {
    path: "/catelist",
    component: () => import("../pages/catelist.vue"),
    meta:{
      title:'商品列表'
    }
  },
  {
    path: "/searchlist",
    component: () => import("../pages/searchlist.vue"),
    meta:{
      title:'商品搜索'
    }
  },
  {
    path: "/detail",
    component: () => import("../pages/detail.vue"),
    meta:{
      title:'商品详情'
    }
  },
  {
    path: "/register",
    component: () => import("../pages/register.vue"),
    meta:{
      title:'注册'
    }
  },
  {
    path: "/login",
    component: () => import("../pages/login.vue"),
    meta:{
      title:'登录'
    }
  },
  {
    path: "/order",
    component: () => import("../pages/order.vue"),
    meta:{
      title:'确认订单'
    }
  },
  {
    path: "/address",
    component: () => import("../pages/address"),
    meta:{
      title:'地址管理'
    }
  },
  {
    path: "/newaddress",
    component: () => import("../pages/newAddress"),
    meta:{
      title:'新增地址'
    }
  },
  {
    path: "/pay",
    component: () => import("../pages/pay.vue"),
    meta:{
      title:'支付页面'
    }
  },
  {
    path: "*",
    redirect: "/index",
  },
];

const router = new VueRouter({
  routes,
  // 滚动行为
  scrollBehavior(to, from, position) {
    // console.log(position, "x,y的位置");
    if (position) {
      return position;
    } else {
      return {
        x: 0,
        y: 0,
      };
    }
  },
});

router.beforeEach((to, from, next) => {
//   // 判断是不是登录页
  if (to.path == "/login") {
    // 是登录页
    next();
    return;
  }
  if (to.path == "/register") {
    next('/register');
    return;
  }

  // 非登录页，判断用户是否登录
  if (sessionStorage.getItem("userinfo")) {
    next();
  } else {
    next("/login");
  }
});

export default router;
